package com.hotlcc.bark.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hotlcc.bark.controller.vo.DevicesVO;
import com.hotlcc.bark.service.DevicesService;
import com.hotlcc.bark.service.converter.DevicesConverter;
import com.hotlcc.bark.service.dto.DevicesDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;

/**
 * 注册 Controller
 */
@RestController
@Validated
public class RegisterController {
    @Autowired
    private DevicesService devicesService;

    /**
     * 注册设备
     *
     * @param deviceToken 设备Token
     * @param deviceKey   推送Key
     */
    @RequestMapping(value = "/register", method = {RequestMethod.GET, RequestMethod.POST})
    public DevicesVO register(@RequestParam("devicetoken") @NotBlank(message = "设备Token不允许为空") String deviceToken,
                              @RequestParam(value = "key", required = false) String deviceKey) {
        if (StrUtil.isBlank(deviceKey)) {
            deviceKey = IdUtil.simpleUUID();
        }
        DevicesDTO dto = devicesService.save(deviceKey, deviceToken);
        return DevicesConverter.INSTANCE.convertToDevicesVO(dto);
    }

    /**
     * 注册检查
     *
     * @param deviceKey 推送Key
     */
    @GetMapping("/register/{deviceKey}")
    public void register(@PathVariable("deviceKey") String deviceKey) {
        Assert.notNull(devicesService.queryOne(deviceKey), "failed to get [{}] device token from database", deviceKey);
    }
}
